<?php

namespace WebmanGrpc\Examples\Transformer;

use WebmanGrpc\Transformer\RequestTransformerInterface;
use Workerman\Protocols\Http\Request;
use Google\Protobuf\Internal\Message;

/**
 * 示例HTTP到gRPC请求转换器
 * 
 * 将HTTP请求转换为gRPC请求
 */
class ExampleRequestTransformer implements RequestTransformerInterface
{
    /**
     * 转换HTTP请求为gRPC请求
     * 
     * @param Request $httpRequest HTTP请求
     * @return Message gRPC请求消息
     */
    public function transform(Request $httpRequest): Message
    {
        // 获取请求体
        $body = $httpRequest->rawBody();
        $data = json_decode($body, true);
        
        // 创建gRPC请求消息
        $request = new class extends Message {
            protected $name;
            protected $age;
            protected $email;
            
            public function setName($name) {
                $this->name = $name;
            }
            
            public function getName() {
                return $this->name;
            }
            
            public function setAge($age) {
                $this->age = $age;
            }
            
            public function getAge() {
                return $this->age;
            }
            
            public function setEmail($email) {
                $this->email = $email;
            }
            
            public function getEmail() {
                return $this->email;
            }
        };
        
        // 设置请求字段
        $request->setName($data['name'] ?? 'World');
        $request->setAge($data['age'] ?? 0);
        $request->setEmail($data['email'] ?? '');
        
        return $request;
    }
}